#include "config.h"

#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/mman.h>

#define DBG_SUBSYS S_LIBTASK

#include "yid.h"
#include "schedule.h"

#include "recovery.h"

/**
 * @file 调度恢复和平衡任务，恢复任务优先于平衡
 *
 */

#define RECOVERY_GLOBAL_WAITTIME  60

typedef struct {
        int flag;
        int wait;
        sem_t sem;
} recovery_global_flag;


static recovery_global_flag _recovery_global_flag;

int recovery_global_flag_init()
{
        int ret;

        _recovery_global_flag.flag = FALSE;
        _recovery_global_flag.wait = FALSE;

        ret = sem_init(&_recovery_global_flag.sem, 0, 0);
        if (ret < 0) {
                ret = errno;
        }

        return ret;
}

inline int recovery_global_flag_get()
{
        return _recovery_global_flag.flag ;
}

inline int recovery_global_flag_set()
{
        _recovery_global_flag.flag = TRUE;
        return 0;
}

int recovery_global_flag_post()
{
        int ret = 0;

        _recovery_global_flag.flag = FALSE;
        if (_recovery_global_flag.wait) {
                ret = sem_post(&_recovery_global_flag.sem);
        }

        return ret;
}

int recovery_global_flag_wait()
{
        int ret;

        while (_recovery_global_flag.flag) {
                _recovery_global_flag.wait = TRUE;
                ret = _sem_timedwait1(&_recovery_global_flag.sem, RECOVERY_GLOBAL_WAITTIME);
                if (unlikely(ret)) {
                        if (ret == ETIMEDOUT) {
                                continue;
                        }

                } else {
                        break;
                }
        }
        _recovery_global_flag.wait = FALSE;

        return 0;
}
